#include "Camera.h"
#include "RayTracer.h"
#include "Scene.h"
#include "RayTracer.h"
#include "RayTraceThread.h"

void RayTraceThread::vProcess()
{
    while(m_tActive)
    {
        if(m_shouldWait)
        {
            ResetEvent(m_event);
            DWORD d = WaitForSingleObject(m_event, INFINITE);
            if(d == WAIT_FAILED)
            {
                int test = 0;
            }
        }
        if(m_tActive && !m_shouldWait)
        {
            Color finalColor;
            Ray ray;
            ray.m_origin = (m_cam->GetPos());

            for(int x = m_startX; x < m_finishX; ++x )
                for(int y = m_startY; y < m_finishY; ++y)
                {
                    m_cam->ComputeDirection(x,y, &ray.m_dir,m_scene);
                    ray.m_depth = -1.0f;
                    ray.m_hitObject = NULL;
                    //Trace it
                    finalColor = m_rt->TraceRay(ray);
                    if(m_scene->TrySetDepth(x,y,ray.m_depth))
                    {
                        m_scene->SetPixelColor(x, y, finalColor);
                    }
                }
        }        
        //if no more jobs left, notifty scene and then puase yourself
        m_scene->ThreadFinished();
        vPause();
    }    
}

//void RayTraceThread::AntiAlias()
//{
//    Color finalColor;
//    Ray ray;
//    ray.m_origin = (m_cam->GetPos());
//
//    for(int x = m_startX; x < m_finishX; x+=2 )
//        for(int y = m_startY; y < m_finishY; y+=2)
//        {
//            m_cam->ComputeDirection(x,y, &ray.m_dir,m_scene);
//            //Trace it
//            finalColor = m_rt->TraceRay(ray);
//            m_cam->ComputeDirection(x,y+1, &ray.m_dir,m_scene);
//            finalColor += m_rt->TraceRay(ray);
//            m_cam->ComputeDirection(x+1,y, &ray.m_dir,m_scene);
//            finalColor += m_rt->TraceRay(ray);
//            m_cam->ComputeDirection(x+1,y+1, &ray.m_dir,m_scene);
//            finalColor += m_rt->TraceRay(ray);
//            finalColor *= 0.25f;
//            m_scene->SetPixelColor(x, y, finalColor);
//            m_scene->SetPixelColor(x, y+1, finalColor);
//            m_scene->SetPixelColor(x+1, y, finalColor);
//            m_scene->SetPixelColor(x+1, y+1, finalColor);
//        }
//}